import 'dart:convert';
import '../models/base_model.dart';
import '../../constants/enums/user_role.dart';
import 'package:meta/meta.dart';

/// 用户数据模型
class UserModel {
  final String id;
  final String name;
  final String email;
  final String? avatarUrl;
  final UserRole role; // 使用枚举类型
  final DateTime? registrationDate;
  final String? bio; // 用户简介
  final String? phone;
  final bool isActive;

  UserModel({
    required this.id,
    required this.name,
    required this.email,
    this.avatarUrl,
    this.role = UserRole.user, // 提供默认值
    this.registrationDate,
    this.bio,
    this.phone,
    this.isActive = true,
  });

  /// 从 JSON 创建 UserModel
  factory UserModel.fromJson(Map<String, dynamic> json) {
    return UserModel(
      id: json['id'] as String? ?? '',
      // 优先使用 displayName，其次 username，最后 name
      name: json['displayName'] as String? ?? 
            json['username'] as String? ?? 
            json['name'] as String? ?? 'Unknown User',
      email: json['email'] as String? ?? '',
      avatarUrl: json['avatarUrl'] as String?,
      role: UserRole.fromString(json['role']?.toString() ?? 'user'),
      registrationDate: json['registrationDate'] != null
          ? DateTime.tryParse(json['registrationDate'] as String)
          : null,
      bio: json['bio'] as String?,
      phone: json['phone'] as String?,
      isActive: json['isActive'] as bool? ?? true,
    );
  }

  /// 将 UserModel 转换为 JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name, // 统一使用 name
      'username': name, // 兼容旧字段（如果需要）
      'displayName': name, // 兼容旧字段（如果需要）
      'email': email,
      'avatarUrl': avatarUrl,
      'role': role.code, // 存储角色代码
      'registrationDate': registrationDate?.toIso8601String(),
      'bio': bio,
      'phone': phone,
      'isActive': isActive,
    };
  }
  
  /// 创建一个 UserModel 的副本，但用给定的字段替换
  UserModel copyWith({
    String? id,
    String? name,
    String? email,
    String? avatarUrl,
    UserRole? role,
    DateTime? registrationDate,
    String? bio,
    String? phone,
    bool? isActive,
  }) {
    return UserModel(
      id: id ?? this.id,
      name: name ?? this.name,
      email: email ?? this.email,
      avatarUrl: avatarUrl ?? this.avatarUrl,
      role: role ?? this.role,
      registrationDate: registrationDate ?? this.registrationDate,
      bio: bio ?? this.bio,
      phone: phone ?? this.phone,
      isActive: isActive ?? this.isActive,
    );
  }

  @override
  String toString() {
    return 'UserModel(id: $id, name: $name, email: $email, role: ${role.code})';
  }
} 